package com.erpoa.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.erpoa.annotation.DataBase;
import com.erpoa.constants.DataSourceNames;
import com.erpoa.dto.BatchMatCombLine;
import com.erpoa.dto.BatchMatCombineMain;
import com.erpoa.entity.PackMessageByMerge;
import com.erpoa.mapper.BatchMergeMapper;
import com.erpoa.service.BatchMergeService;
import com.erpoa.utils.PDAException;
import com.erpoa.utils.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * @author chenjimin
 * @Title: BatchMergeServiceImpl
 * @ProjectName oaerp
 * @Description: TODO
 * @date 2021/1/2813:29
 */
@Service
public class BatchMergeServiceImpl implements BatchMergeService {
    private static final Logger logger = LoggerFactory.getLogger(BatchMergeServiceImpl.class);

    @Autowired
    private BatchMergeMapper batchMergeMapper;

    @Override
    @DataBase(DataSourceNames.DSX5)
    @Transactional()
    public List<BatchMatCombineMain> selectBatchMergeToday(PackMessageByMerge packMessage) {
        if (StringUtil.isEmpty(packMessage.getTime())) {
            packMessage.setCombineNumber("45");
        }
        return batchMergeMapper.selectBatchMergeToday(packMessage);
    }

    @Override
    @DataBase(DataSourceNames.DSX5)
    @Transactional()
    public JSONObject querytcPgenFile(PackMessageByMerge packMessage) {
        //TODO CJM
        //int countright = this.batchMergeMapper.queryRight(packMessage.getUser().getsCode());
        int countright = this.batchMergeMapper.queryRight("147042");
        if (countright <= 0) {
            throw new PDAException("当前用户没有厂级或者车间权限，请联系相关人员维护，TC_PGEN_FILE,即将退出当前界面！");
        }

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("success", "厂级或者车间权限校验通过，开始拉取批次合并数据！");
        return jsonObject;


    }

    @Override
    @DataBase(DataSourceNames.DSX5)
    @Transactional()
    public JSONObject selectSequnce(PackMessageByMerge packMessage) {

        Integer minCount = 0;
        /*
        try {
            minCount= commonDataMapper.getSequence(seq);
        }catch (Exception e){
            e.printStackTrace();
            commonDataMapper.createSequence(seq, "1"); // todo cjm 上线1开始
            minCount= commonDataMapper.getSequence(seq);
        }*/

        JSONObject jsonObject = new JSONObject();
        SimpleDateFormat sdf = new SimpleDateFormat("yyMMdd");
        String sdfdate = "HJ" + sdf.format(new Date());


        try {
            minCount = batchMergeMapper.getSequence(sdfdate);
        } catch (Exception e) {
            e.printStackTrace();
            batchMergeMapper.createSequence(sdfdate, "1"); // todo cjm 上线1开始
            minCount = batchMergeMapper.getSequence(sdfdate);
        }

        if (minCount > 0) {
            jsonObject.put("success", "成功获取到合并单号流水码！");
            sdfdate = "HB" + sdfdate + minCount;
            jsonObject.put("sdfdate", sdfdate);
            return jsonObject;
        }

        jsonObject.put("error", "获取合并单号流水码失败，请联系管理员！");

        return jsonObject;
    }

    @Override
    @DataBase(DataSourceNames.DSX5)
    @Transactional()
    public List<BatchMatCombLine> selectBatchMergeLine(PackMessageByMerge packMessage) {
        if (StringUtil.isEmpty(packMessage.getCombineNumber())) {
            throw new PDAException("合并单号不能为空，请重新选中列表！");
        }

        List<BatchMatCombLine> lines = this.batchMergeMapper.selectBatchMergeLine(packMessage);
        if (StringUtil.isEmpty(lines)) {
            throw new PDAException("没有任何数据，请确认！");
        }

        return lines;
    }


    @Override
    @DataBase(DataSourceNames.DSX5)
    @Transactional()
    public JSONObject updateMergeLineByScan(PackMessageByMerge packMessage) {
        if (StringUtil.isEmpty(packMessage.getCombineNumber())) {
            throw new PDAException("合并单号不能为空，请确认！");
        }

        List<BatchMatCombLine> list = this.batchMergeMapper.selectBatchsMergeLine(packMessage.getCombineNumber());
        if (StringUtil.isEmpty(list) || list.size() < 1) {
            if ("45".equals(packMessage.getTime())) {
                throw new PDAException("两个以上批次号才保存，请确认！");
            } else {
                throw new PDAException("两个以上批次号才提交，请确认！");
            }


        }


        if (list.size() <= 1) {
            if ("45".equals(packMessage.getTime())) {
                throw new PDAException("两个以上批次号才保存，请确认！");
            } else {
                throw new PDAException("两个以上批次号才提交，请确认！");
            }
        }

        Double qtytemp = 0D;
        for (BatchMatCombLine temp : list) {

            qtytemp = qtytemp + temp.getOldQty();

        }


        BatchMatCombineMain batchMatCombineMain = this.batchMergeMapper.selectBatchMergeLineByComnumber(packMessage.getCombineNumber());
        if (StringUtil.isNull(batchMatCombineMain)) {
            throw new PDAException("主表数据不存在,请确认！");
        }


        batchMatCombineMain.setNewQty(qtytemp);

        if ("Y".equals(batchMatCombineMain.getMgStatus())) {
            if ("45".equals(packMessage.getTime())) {
                throw new PDAException("当前单号已合并，不允许提交！");
            } else {
                throw new PDAException("当前单号已合并，不允许保存！");
            }
        } else {
            if (StringUtil.isNotEmpty(batchMatCombineMain.getNewBarCode())) {
                if (!"45".equals(packMessage.getTime())) {
                    throw new PDAException("当前新条码已生成，不允许保存！");
                } else {

                    if ("45".equals(packMessage.getTime())) {
                        batchMatCombineMain.setMgStatus("Y");
                    } else {
                        batchMatCombineMain.setMgStatus("N");
                    }
                    int scanMaster = this.batchMergeMapper.updateBatchMailstatus(batchMatCombineMain);
                    if (scanMaster <= 0) {
                        throw new PDAException("主表更新失败，请确认！");
                    }


                    try {


                        int insertemo = this.batchMergeMapper.insertBatchmatByMain(batchMatCombineMain, list.get(0));
                        if (insertemo <= 0) {
                            throw new PDAException("批次表生成失败，请确认！");
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                        if (e.getMessage().contains("ORA-00001")) {
                            throw new PDAException("批次表已生成，请确认！");
                        }
                    }
                    for (BatchMatCombLine temp : list) {
                        //更新原始批次号
                        int updatescanint = this.batchMergeMapper.updateBatchScan(temp);
                        if (updatescanint <= 0) {
                            throw new PDAException("原始数据更新失败，批次条码为：" + temp.getFbarcode() + "请确认！");
                        }
                        qtytemp = qtytemp + temp.getOldQty();

                    }

                }

            } else {
                //开始获取批次号
                String newBarCode = this.createNewBarCode(batchMatCombineMain, list.get(0));
                batchMatCombineMain.setNewBarCode(newBarCode);
                if ("45".equals(packMessage.getTime())) {
                    batchMatCombineMain.setMgStatus("Y");
                } else {
                    batchMatCombineMain.setMgStatus("N");
                }
                int scanMaster = this.batchMergeMapper.updateBatchMailnewBarCode(batchMatCombineMain);
                if (scanMaster <= 0) {
                    throw new PDAException("主表更新失败，请确认！");
                }


            }


        }


        JSONObject jsonObject = new JSONObject();
        jsonObject.put("success", "成功");
        jsonObject.put("status", batchMatCombineMain.getMgStatus());
        jsonObject.put("newBarCode", batchMatCombineMain.getNewBarCode());
        return jsonObject;
    }

    @Override
    @DataBase(DataSourceNames.DSX5)
    @Transactional()
    public JSONObject delMergeLineByScan(PackMessageByMerge packMessage) {
        if (StringUtil.isEmpty(packMessage.getCombineNumber())) {
            throw new PDAException("合并单号不能为空，请确认！");
        }

        BatchMatCombineMain batchMatCombineMain = this.batchMergeMapper.selectBatchMergeLineByComnumber(packMessage.getCombineNumber());
        if (StringUtil.isNull(batchMatCombineMain)) {
            throw new PDAException("主表数据不存在,请确认！");
        }


        if ("Y".equals(batchMatCombineMain.getMgStatus())) {
            throw new PDAException("当前单号已合并，不允许删除,请确认！");
        }


        int lineint = this.batchMergeMapper.dellineByComnumber(packMessage.getCombineNumber());
        int mainint = this.batchMergeMapper.delmainByComnumber(packMessage.getCombineNumber());
        if (mainint <= 0) {
            throw new PDAException("删除失败,请确认！");
        }

        JSONObject jsonObject = new JSONObject();

        jsonObject.put("success", "处理完成！");

        return jsonObject;
    }

    @Override
    @DataBase(DataSourceNames.DSX5)
    @Transactional()
    public JSONObject selectBatchNoByPackmessage(PackMessageByMerge packMessage) {
        JSONObject jsonObject = new JSONObject();
        if (StringUtil.isEmpty(packMessage.getCombineNumber())) {
            throw new PDAException("合并单号不能为空，请确认！");
        }
        BatchMatCombineMain batchMatCombineMain = this.batchMergeMapper.selectBatchMergeLineByComnumber(packMessage.getCombineNumber());
        if (StringUtil.isNull(batchMatCombineMain) || StringUtil.isEmpty(batchMatCombineMain.getNewBarCode())) {
            throw new PDAException("未获取到新条码号,请确认！");
        }

        if (!"Y".equals(batchMatCombineMain.getMgStatus())) {
            throw new PDAException("当前合并单号未合并，不能打印,请确认！");
        }

        jsonObject.put("newBarCode", batchMatCombineMain.getNewBarCode());
        jsonObject.put("success", "处理完成！");

        return jsonObject;
    }

    @Override
    @DataBase(DataSourceNames.DSX5)
    @Transactional()
    public JSONObject selectBatchMergeLineByScan(PackMessageByMerge packMessage) {

        JSONObject jsonObject = new JSONObject();
        if (StringUtil.isEmpty(packMessage.getCombineNumber())) {
            throw new PDAException("合并单号不能为空，请确认！");
        }

        //查询是否已存在
        int countcombinenumber = this.batchMergeMapper.countBatchMergeLineCombinenumber(packMessage);
        if (countcombinenumber > 0) {
            throw new PDAException("当前批次号已存在，请确认,请从主页点击进入！");
        }

        //查询数量是否满足
        int countLine = this.batchMergeMapper.countBatchMergeLineBycombineNumber(packMessage);
        if (countLine == 2) {
            throw new PDAException("批次号已存在两条，请确认！");
        }
        if (countLine == 1) {

            //在查询扫描的
            BatchMatCombLine batchMatCombLinescan = this.batchMergeMapper.selectBatchMergeLineByNowHasdto(packMessage.getmBarcode());
            if (StringUtil.isNull(batchMatCombLinescan)) {
                throw new PDAException("当前扫描批次号不正确，请确认！");
            }
            batchMatCombLinescan.setCombineNumber(packMessage.getCombineNumber());
            batchMatCombLinescan.setBfCreateper(packMessage.getUser().getsCode());
            //查询现有的
            BatchMatCombLine fbarcodehas = this.batchMergeMapper.selectBatchMergeLineByNowHas(packMessage);

            if (!batchMatCombLinescan.getFfactorycode().equals(fbarcodehas.getFfactorycode())) {
                throw new PDAException("当前扫描批次号与现存厂别不一致，请确认！");
            }
            if (!batchMatCombLinescan.getFworkshopcode().equals(fbarcodehas.getFworkshopcode())) {
                throw new PDAException("当前扫描批次号与现存车间不一致，请确认！");
            }
            if (!batchMatCombLinescan.getFvendercode().equals(fbarcodehas.getFvendercode())) {
                throw new PDAException("当前扫描批次号与现存供应商不一致，请确认！");
            }

            if (!batchMatCombLinescan.getFmatcode().equals(fbarcodehas.getFmatcode())) {
                throw new PDAException("当前扫描批次号与现存料号不一致，请确认！");
            }
            if (!batchMatCombLinescan.getFtype().equals(fbarcodehas.getFtype())) {
                throw new PDAException("当前扫描批次号与现存型号不一致，请确认！");
            }
            if (!batchMatCombLinescan.getFcolor().equals(fbarcodehas.getFcolor())) {
                throw new PDAException("当前扫描批次号与现存颜色不一致，请确认！");
            }

            //先更新主表
            BatchMatCombineMain batchMain = new BatchMatCombineMain();
            batchMain.setCombineNumber(packMessage.getCombineNumber());
            batchMain.setCreater(packMessage.getUser().getsCode());
            batchMain.setFbatchno(packMessage.getmBarcode());
            batchMain.setNewQty(batchMatCombLinescan.getOldQty() + batchMatCombLinescan.getOldQty());
            jsonObject.put("fqty", batchMatCombLinescan.getOldQty() + batchMatCombLinescan.getOldQty());
            batchMain.setFFactoryCode(batchMatCombLinescan.getFfactorycode());
            batchMain.setFWorkShopCode(batchMatCombLinescan.getFworkshopcode());
            //开始获取批次号
            // String  newBarCode =  this.createNewBarCode(batchMain,batchMatCombLinescan);
            //  batchMain.setNewBarCode(newBarCode);

            int scanMaster = this.batchMergeMapper.updateBatchMailScan(batchMain);
            if (scanMaster <= 0) {
                throw new PDAException("主表更新失败，请确认！");
            }

            batchMatCombLinescan.setCombineNumber(batchMain.getCombineNumber());
            batchMatCombLinescan.setBfCreateper(batchMain.getCreater());
            //校验完成插入数据
            int scanInt = this.batchMergeMapper.insertBatchScan(batchMatCombLinescan);
            if (scanInt > 0) {


            } else {
                throw new PDAException("当前扫描数据插入失败，请确认！");
            }

            jsonObject.put("success", "处理完成！");

            return jsonObject;

        } else {

            //在查询扫描的
            BatchMatCombLine batchMatCombLinescan = this.batchMergeMapper.selectBatchMergeLineByNowHasdto(packMessage.getmBarcode());
            if (StringUtil.isNull(batchMatCombLinescan)) {
                throw new PDAException("当前扫描批次号不正确，请确认！");
            }

            //先更新主表
            BatchMatCombineMain batchMain = new BatchMatCombineMain();
            batchMain.setCombineNumber(packMessage.getCombineNumber());
            batchMain.setCreater(packMessage.getUser().getsCode());
            batchMain.setFbatchno(packMessage.getmBarcode());
            batchMain.setNewQty(batchMatCombLinescan.getOldQty());
            jsonObject.put("fqty", batchMain.getNewQty());
            batchMain.setFFactoryCode(batchMatCombLinescan.getFfactorycode());
            batchMain.setFWorkShopCode(batchMatCombLinescan.getFworkshopcode());
            //开始获取批次号
            //  String  newBarCode =  this.createNewBarCode(batchMain,batchMatCombLinescan);
            // batchMain.setNewBarCode(newBarCode);

            int scanMaster = this.batchMergeMapper.insertBatchMailScan(batchMain);
            if (scanMaster <= 0) {
                throw new PDAException("主表插入失败，请确认！");
            }

            batchMatCombLinescan.setCombineNumber(batchMain.getCombineNumber());
            batchMatCombLinescan.setBfCreateper(batchMain.getCreater());
            //校验完成插入数据

            int scanInt = this.batchMergeMapper.insertBatchScan(batchMatCombLinescan);
            if (scanInt > 0) {
                /*//更新原始批次号
                int updatescanint = this.batchMergeMapper.updateBatchScan(batchMatCombLinescan);
                if (updatescanint<=0){
                    throw new PDAException("原始数据更新失败，请确认！");
                }*/

            } else {
                throw new PDAException("当前扫描数据插入失败，请确认！");
            }


            jsonObject.put("success", "处理完成！");

            return jsonObject;

        }


    }


    private String createNewBarCode(BatchMatCombineMain batchMain, BatchMatCombLine batchMatCombLine) {
        StringBuffer sb = new StringBuffer();

        sb.append(batchMatCombLine.getFvendercode().replaceAll("MGG", ""));
        sb.append("/");
        sb.append(batchMatCombLine.getFtype());
        sb.append("/");
        sb.append(batchMatCombLine.getFcolor());
        sb.append("/");
        sb.append(batchMain.getNewQty());
        sb.append("/");
        String batchTemp1 = batchMatCombLine.getFbarcode();
        String batchTemp = batchTemp1.substring(batchTemp1.lastIndexOf("/") + 1, batchTemp1.length());
        if (StringUtil.isEmpty(batchTemp)) {
            throw new PDAException("当前条码编码规则错误，请确认！");
        }
        if (batchTemp.length() > 8) {
            sb.append(batchTemp.substring(0, 8));
            sb.append("HB");
        } else {
            sb.append(batchTemp + "HB");
        }


        return sb.toString();
    }
}
